package com.dx.mes.web.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.dx.common.table.ppt.Bis_uas_fnc_grp;
import com.dx.common.table.ppt.Bis_uas_grp;
import com.dx.mes.common.core.his.HistoryManager;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.uas.service.IBisUasFunGrpService;
import com.dx.mes.web.common.authorization.manager.TokenManager;
import com.dx.mes.web.common.authorization.model.TokenModel;
import com.dx.mes.web.common.config.Constants;
import com.dx.mes.web.common.service.ISendMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class SendMessageController {
	@Value("${common.url}")
	private String commonURL;
	@Autowired
	private TokenManager manager;
	@Resource
	private HistoryManager historyManager;
	@Resource
	private ISendMessageService sendMessageServiceImpl;

	@Resource
	private IBisUasFunGrpService bisUasFunGrpService;


	//基于拦截器
	@RequestMapping("{page}/{pageDe}/loginRtn.do")
	public String loginRtn(@PathVariable String page, @PathVariable String pageDe, HttpServletRequest request) {
		String page_rtn = pageDe.substring(0, pageDe.indexOf("_"));
		return page_rtn;
	}
	//检查按钮
	@RequestMapping("checkUserAuthority.do")
	@ResponseBody
	public boolean checkUserPermisson(HttpServletRequest request) {
		boolean flag = true;
		String function_code = request.getParameter("function_code");
		String userID = (String)request.getSession().getAttribute("userid");
		//首先判断是否为管理员
		List<Bis_uas_grp> adminList = bisUasFunGrpService.getAdminFlag(userID);
		if (adminList != null && adminList.size() > 0) {
			flag = true;
			return flag;
		}
		//判断权限
		List<Bis_uas_fnc_grp> permission = bisUasFunGrpService.getPermission(userID);
		permission = permission == null ? new ArrayList<>() : permission;
		List<String> permissionList = permission.stream().map(p -> p.getId().getFunc_code_fk()).collect(toList());
		//List<String> perList = permissionList.stream().map(per -> per.substring(0, per.lastIndexOf("_"))).collect(toList());
		boolean hasAuth =  permissionList.stream().anyMatch(function_code::equals);
		if (hasAuth) {
			flag = true;
			return flag;
		} else {
			flag = false;
			return flag;
		}
	}

	//退出
	@RequestMapping("logout.do")
	public String logout(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String ssoName1 =(String) request.getSession().getAttribute("user");
		String ssoName = URLEncoder.encode(ssoName1,"utf-8");
		String sso1 =(String) request.getSession().getAttribute("userid");
		String contextPath = request.getContextPath();
		String sso = URLEncoder.encode(sso1,"utf-8");
		//清空session和cookies
		request.getSession().invalidate();
		// 向客户端写入cookie，名为为ssoName
		Cookie c = new Cookie("ssoName", ssoName);
		c.setPath("/");
		c.setMaxAge(0);
		response.addCookie(c);// 把cookie添加到response中
		// 向客户端写入cookie，名为为ssoName
		Cookie c1 = new Cookie("sso", sso);
		c1.setPath("/");
		c1.setMaxAge(0);
		response.addCookie(c1);// 把cookie添加到response中
		Object loginErr = request.getSession().getAttribute("loginErr");
//		return "redirect:http://localhost:8080/mes-dx-web-login/index.jsp";
		return "redirect:"+commonURL+contextPath+"/index.jsp";
	}

	@RequestMapping("editPwd.do")
	@ResponseBody
	public String editPwd(HttpServletRequest request) {
		String userid = (String)request.getSession().getAttribute("userid");
		String newPwd = request.getParameter("pwd");
		bisUasFunGrpService.editPwdById(userid, newPwd);
		return "true";
	}

	@RequestMapping("sendMsg.do")
	@ResponseBody
	public String sendMessage(String trxId, String strInMsg,HttpServletRequest request) {
		String evt_no = GUIDGenerator.javaGUID();
		if (trxId.equals("ISMODALIVE")) {
			    JSONObject json =new JSONObject();
				trxId = "FBPMESBC";
				moaliveSend(trxId, json,"brm_flg");
				trxId = "FPPMESBC";
				moaliveSend(trxId, json,"process_flg");
				trxId = "FTPMESBC";
				moaliveSend(trxId, json,"tool_flg");
				trxId = "FSPMESBC";
				moaliveSend(trxId, json,"special_flg");

			return json.toString();

		}
		Object user = request.getSession().getAttribute("user");
		String message = sendMessageServiceImpl.sendMesage(trxId, evt_no, strInMsg);
		if (!Util.isSpaceCheck(message) && historyManager.isTransactionSuccessed(message)) {
			historyManager.sendHistoryMessageToRabbitMQ(evt_no);
		}
		return message;
	}
	
	private void moaliveSend(String trxId, JSONObject json,String flg){
		String evt_no = GUIDGenerator.javaGUID();
		String strInMsg = "{\"trx_id\":\""+trxId+"\"}";
		String message = sendMessageServiceImpl.sendMesage(trxId, evt_no, strInMsg);
		if (StringUtils.isNoneEmpty(message)) {
			json.put(flg, "Y");
		}else{
			json.put(flg, "N");
		}
	}

	@RequestMapping("/home.do")
	public String rtHome(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		if (request.getSession().getAttribute("user") == null) {
			// 获取request中所有的Cookie，并放在数组中
			Cookie[] cs = request.getCookies();
			// 若Cookie不为空，则遍历所有的Cookie中所有的记录
			if (cs != null && cs.length > 0) {
				for (Cookie c : cs) {
					String cName = c.getName();
					// 查找当前用户的Cookie（此处为sso标识）
					if (cName.equals("ssoName")) {
						// 获取sso中对应的值，即：用户名userName
						String userName1 = c.getValue();
						String userName = URLDecoder.decode(userName1, "utf-8");
						// 把用户名userName放在session中
						request.getSession().setAttribute("user", userName);
					}if (cName.equals("sso")) {
						// 获取sso中对应的值，即：用户名userName
						String userid1 = c.getValue();
						String userid = URLDecoder.decode(userid1, "utf-8");
						// 把用户名userName放在session中
						request.getSession().setAttribute("userid", userid);
					}
				}
			}
		}
		String contextPath = request.getContextPath();
//		return "redirect:http://localhost:8080/mes-dx-web-login/home.jsp";
		return  "redirect:"+commonURL+contextPath+"/home.jsp";
	}

	@RequestMapping("appLogout.do")
	@ResponseBody
	public JSONObject appLogout(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnsupportedEncodingException {
		response.setHeader("content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		//如果不是映射到方法直接通过
//		if (!(handler instanceof HandlerMethod)) {
//			return true;
//		}
//		HandlerMethod handlerMethod = (HandlerMethod) handler;
//		Method method = handlerMethod.getMethod();
		//从header中得到token
		String authorization = request.getHeader(Constants.AUTHORIZATION);
//		authorization = "admin_644a57c80eb54c028a87fe9249b9b330";
		//验证token
		TokenModel model = manager.getToken(authorization);
		manager.deleteToken(model.getUserId());
		JSONObject msgJson = new JSONObject();
		msgJson.put("rtn_code","0000000");
		msgJson.put("rtn_mesg","SUCCESS");
		return msgJson;
	}


}
